<!-- 新建地址 -->
<template>
	<view class="new-address-page">
		<view class="content-card p-bottom70">
			<view class="address">
				<view class="view_margin">姓名</view>
				<!-- v-model（双 向数据绑定）="consignee" 是用来传值的 consignee是后端的名字 -->
				<input placeholder-class="input-color" class="input-class" v-model="form.name" placeholder="请填写姓名" />
			</view>
			<view class="address">
				<!-- &nbsp;与letter-spacing: 2rpx;联合使用 -->
				<view class="view_margin">手机号码</view>
				<input placeholder-class="input-color" type="number" maxlength="11" v-model="form.phone"
					class="input-class" placeholder="请填写手机号码" />
			</view>
			<view class="address">
				<view class="view_margin">所在地区</view>
				<pca-picker-cc v-on:getAddressResultObj="getAddressResultObj" :addressList.sync="addressList">
					<view class="uni-input">{{ addressList.join(' ') }}</view>
				</pca-picker-cc>
			</view>
			<!-- <view class="address flex-between" @click="toPosition">
				<view class="flex-align-center address-width">
					<view>详细地址</view>
					<input placeholder-class="input-color" :disabled="true" class="input-class" v-model="address" placeholder="街道、楼牌号等" />
				</view>
				<view class="flex-end positioning-cls">
					<image src="/static/positioning.png"></image>
					<view>定位</view>
				</view>
			</view> -->

			<view class="textarea-box">
				<textarea placeholder-style="font-size:28rpx;" v-model="form.address" placeholder="输入详细地址"
					maxlength="20" @input="descInput" style="height: 100rpx;" />
				<view class="textarea-color">{{ remnant }}/20</view>
			</view>
		</view>

		<view class="content-card padding30">

			<view class="flex-between">
				<view class="flex-columns">
					<view class="m-bottom16">设置默认地址</view>
					<text class="color666 font24">提醒：每次下单会默认推荐使用改地址</text>
				</view>
				<!-- switch 开关 -->
				<switch color="#ff9534" :checked="form.status==1?true:false" style="zoom: 0.7;" @change="switch1Change">
				</switch>
			</view>
			<!-- <view @click="addressClick()" style="margin-top: 30rpx;color: rgb(255, 149, 52);">清空地址</view> -->
			<view @click="determine()" class="determine_btn">{{isEdit?'修改地址':'保存'}}</view>
		</view>
		<!-- 添加标签 弹出框 -->
		<sunui-popup ref="pop">
			<template v-slot:content>
				<view class="v-pop-cls flex-column">
					<image src="/static/close.png" @click="closeTag"></image>
					<text>添加标签</text>
					<input maxlength="6" placeholder="请输入1到6个字标签" v-model="singleLabel" />
					<view class="flex" @click="singleLabelClick()">{{isEdit?'修改地址':'保存'}}</view>
				</view>
			</template>
		</sunui-popup>
	</view>
</template>

<script>
	import antiThrottling from '@/utils/antiThrottling.js';
	export default {
		data() {
			return {
				latitude: '',
				longitude: '',
				singleLabel: '', // 单个标签覆盖

				checked: false,
				region: ['', '', ''],
				addressList: ["", "", ""],
				regions: '省市区县、乡镇等',
				/* 用于同一处的变量 可以用对象{}定义 包裹起来,用的时候 对象名.对象变量 就好了 */
				index: 0,
				id: '',
				consignee: '',
				mobile: '',
				// 省
				province: '',
				// 市
				city: '',
				// 区
				district: '',



				defaultNot: '',
				hintIndex: -1, //标签选中index

				detailsAddress: '', //更详细的地址，可不输入
				remnant: 0,
				token: uni.getStorageSync('login').token,
				isEdit: false,
				form: {
					province_id: '',
					city_id: '',
					county_id: '',
					province_name: '',
					city_name: '',
					county_name: '',
					address: '',
					// 默认地址1 2 就是一个地址
					status: '1',
					name: '',
					phone: ''
				}
			};
		},
		// 页面一进去就会执行
		onShow() {
			this.$at.releaseKey('submitAll');

		},
		// options是传参中 有参数必须需要的，没有传参则不需要
		onLoad(options) {
			console.log(options)
			if (options.id) {
				this.form.id = ''

				this.$sun.assignObject(this.form, {
					...options
				})
				this.addressList[0] = this.form.province_name
				this.addressList[1] = this.form.city_name
				this.addressList[2] = this.form.county_name

				this.isEdit = true

			}

		},

		methods: {
			getAddressResultObj(e) {
				//获取详细的 省/市/区 对象信息,更新时被动调,主动调用请自行设置ref值,方法一致
				console.log(e)
				this.form.city_name = e.city.name
				this.form.city_id = e.city.code
				this.form.county_name = e.county.name
				this.form.county_id = e.county.code
				this.form.province_name = e.province.name
				this.form.province_id = e.province.code

			},
			// 更详细的地址
			descInput(e) {
				this.remnant = e.detail.value.length;
				if (this.remnant >= 20) {
					this.$sun.toast('详细地址输入已达上限', 'none');
				}
			},
			// 去定位
			toPosition() {
				uni.chooseLocation({
					success: res => {
						this.address = res.name;
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						console.log('获取定位信息res============', res);
					}
				});
			},
			handleGetRegion(region) {
				console.log('点击this.region', region);
				this.region = region;
				this.province = region[0].name;
				this.city = region[1].name;
				this.district = region[2].name;
				this.regions = this.province + '-' + this.city + '-' + this.district;
			},





			//点击开关 判断开关是开还是关  switch  开关选择器。
			async  switch1Change(e) {
				if (e.target.value) {
					this.form.status = '1'
					if(this.isEdit){
						const result = await this.$http.post({
							url: this.$api.setDefault,
							data: {
								id:this.form.id
							},
							headers: {
								'Authorization': `Bearer ${this.token}`
							}
						
						})
						if(result.code==0){
							this.$sun.toast(result.msg,'none')
						}else{
							this.$sun.toast(result.msg,'none')
						}
					}
				} else {
					this.form.status = '2'
				}
				
			
				// this.checked = e.target.value;
			},
			//选择省市区  省市区选择器
			bindPickerChange: function(e) {
				this.region[0] = e.target.value[0];
				this.region[1] = e.target.value[1];
				this.region[2] = e.target.value[2];
				this.province = e.target.value[0];
				this.city = e.target.value[1];
				this.district = e.target.value[2];
				this.regions = e.target.value[0] + '-' + e.target.value[1] + '-' + e.target.value[2];
			},
			//点击确定
			determine() {
				if (!this.form.name) {
					this.$sun.toast('请填写姓名', 'none');
					return false;
				} else if (!/^1[3456789]\d{9}$/.test(this.form.phone)) {
					this.$sun.toast('请输入正确的手机号', 'none');
					return false;
					// 当前因为省市区/县 是一起的，所以单判断province（省）
				} else if (!this.form.province_name) {
					this.$sun.toast('请选择省市区/县', 'none');
					return false;
				} else if (!this.form.address) {
					this.$sun.toast('请填写详细地址', 'none');
					return false;
				} else {
					console.log(this.form)
					/* 防抖动节流 */
					this.$at.uniDoFunc({
						key: 'submitAll',
						success: async () => {
							this.$at.lockKey('submitAll');
							const result = await this.$http.post({
								url: this.$api.addressEdit,
								data: {
									...this.form
								},
								headers: {
									'Authorization': `Bearer ${this.token}`
								}

							})

							if (result.code == 0) {


								this.$at.releaseKey('submitAll');


								this.$sun.toast(result.msg, 'none')
								// this.$sun.toast(resPoster.msg, 'none')
								this.$sun.navBack()

							} else {
								this.$at.releaseKey('submitAll');
								this.$sun.toast(resPoster.msg, 'none')
							}


						}
					})
				}
			},
			/* 清空地址 */
			addressClick() {
				/* if中 的=''还是null  是看上面的定义值的 或则后端的返回值，一般都是定义''，如果后端返回的字段非''，则需要让后端改一下哈 */
				if (this.consignee != '' || this.mobile != '' || this.region[0] != '' || this.region[1] != '' || this
					.region[2] != '' || this.address != '') {
					uni.showModal({
						confirmColor: '#14DF79',
						title: '提示',
						content: '确认清空该地址？',
						success: async res => {
							// res.confirm  点击确定  对接口$api.addressDel   传后端参数值id
							if (res.confirm) {
								this.consignee = '';
								this.mobile = '';
								this.region[0] = '';
								this.region[1] = '';
								this.region[2] = '';
								this.address = '';
								this.hintIndex = -1;
								this.latitude = '';
								this.longitude = '';
								this.province = '';
								this.detailsAddress = ''
								this.regions = '省市区县、乡镇等'
							} else if (res.cancel) {
								// 用户点击取消
							}
						}
					});
				} else {
					this.$sun.toast('地址为空');
				}
			},

			//地址详情
			async addressDetails() {
				const result = await this.$http.get({
					url: this.$api.getAddress,
					data: {
						id: this.id
					}
				});
				if (result.code == 200) {
					this.consignee = result.data.consignee;
					this.mobile = result.data.mobile;
					this.province = result.data.province;
					this.city = result.data.city;
					this.district = result.data.district;
					this.regions = this.province + '-' + this.city + '-' + this.district;
					this.address = result.data.address;
					this.checked = result.data.defaultNot == 1 ? true : false;
					this.detailsAddress = result.data.detailsAddress

				} else {
					this.$sun.toast(result.message);
				}
			},

			// 新增地址
			async addressAdds() {
				const result = await this.$http.post({
					url: this.$api.addAddress,
					data: {
						latitude: this.latitude,
						longitude: this.longitude,
						id: this.id ? this.id : '',
						consignee: this.consignee, //姓名
						mobile: this.mobile, //手机号
						province: this.province, //省
						city: this.city, //市
						district: this.district, //区
						address: this.address, //地址
						defaultNot: this.checked ? 1 : 2, // 默认地址：如果点击事件为开 则为1true 否则为2false

						siteId: uni.getStorageSync('siteId'), // 站点id
						userId: uni.getStorageSync('userId'), //登录用户的id
						detailsAddress: this.detailsAddress ? this.detailsAddress : '' //用户手动输入的详细地址
					}
				});
				if (result.code == 200) {
					this.$sun.toast('保存地址成功！');
					setTimeout(() => {
						this.$sun.navBack();
					}, 1000);
					console.log('保存地址result.', result);
				} else {
					this.$sun.toast(result.message);
				}
			},
			// 修改地址
			async addressEdits() {
				const result = await this.$http.put({
					url: this.$api.addAddress,
					data: {
						latitude: this.latitude,
						longitude: this.longitude,
						id: this.id ? this.id : '',
						consignee: this.consignee, //姓名
						mobile: this.mobile, //手机号
						province: this.province, //省
						city: this.city, //市
						district: this.district, //区
						address: this.address, //地址
						defaultNot: this.checked ? 1 : 2, // 默认地址：如果点击事件为开 则为1true 否则为2false

						siteId: uni.getStorageSync('siteId'), // 站点id
						userId: uni.getStorageSync('userId'), //登录用户的id
						detailsAddress: this.detailsAddress ? this.detailsAddress : '' //用户手动输入的详细地址
					}
				});
				if (result.code == 200) {
					this.$sun.toast('修改地址成功！');
					setTimeout(() => {
						this.$sun.navBack();
					}, 1000);
					console.log('修改地址result.', result);
				} else {
					this.$sun.toast(result.message);
				}
			}
		}
	};
</script>

<style lang="less">
	page {
		background-color: #f7f7f7;
	}

	.new-address-page {
		padding-bottom: 260rpx;

		.p-bottom70 {
			padding-bottom: 30rpx;
		}

		.content-card {
			background-color: #ffffff;
			border-radius: 40rpx;
			margin-bottom: 24rpx;

			.address {
				display: flex;
				align-items: center;
				border-bottom: 2rpx solid #f7f7f7;
				padding: 26rpx 0rpx;
				margin: 0 20rpx;

				.view_margin {
					margin: 0rpx 40rpx 0rpx 10rpx;
					width: 20%;
				}

				.input-color {
					color: #999 !important;
					font-size: 24rpx;
				}

				.input-class {
					font-size: 24rpx;
					width: 80%;
					/* 单行省略 */
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 3;
					overflow: hidden;
					-webkit-box-orient: vertical;
				}

				.v-img {
					width: 21rpx;
					height: 20rpx;
					color: #707070;
				}

				.address-width {
					flex: 1;
					margin: 0rpx 40rpx 0rpx 10rpx;

					view {
						width: calc(20% + 55px);
					}
				}

				.positioning-cls {
					width: 70px;

					image {
						width: 28rpx !important;
						height: 28rpx !important;
					}

					view {
						margin-left: 10rpx;
						color: #999;
						font-size: 24rpx;
					}
				}
			}

			// 多行文本
			.textarea-box {
				font-size: 28rpx !important;
				margin: 20rpx;
				border-radius: 20rpx;
				padding: 20rpx 30rpx;
				background: #f6f6f6;
				margin-top: 26rpx;

				.textarea-color {
					color: #999;
				}
			}
		}

		// 设置标签
		.label-set {
			border-bottom: 2rpx solid #f7f7f7;
			margin-bottom: 30rpx;

			.none-cls {
				background-color: #dedede;
			}

			.label-cls,
			.sel-label-cls {
				padding: 4rpx 10rpx;
				min-width: 100rpx;
				border-radius: 60rpx;
				margin: 0 0 20rpx 20rpx;
			}

			.label-cls {
				border: 2rpx solid #dedede;
			}

			.sel-label-cls {
				color: rgb(255, 149, 52);
				;
				background-color: #deffd9;
				border: 2rpx solid #deffd9;
			}

			.p-right42 {
				padding-right: 48rpx !important;
			}

			.hint-img {
				width: 36rpx;
				height: 36rpx;
				position: absolute;
				top: 6rpx;
				right: 10rpx;
			}
		}

		// 删除/清空地址
		.view_delect {
			color: rgb(255, 149, 52);
			;
			margin-top: 42rpx;
		}

		.determine_btn {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 710rpx;
			height: 100rpx;
			border-radius: 56rpx;
			background: linear-gradient(82.57deg, rgb(254, 231, 184) 1.895%, rgb(243, 210, 149) 93.739%);
			color: rgb(122, 85, 32);
			font-size: 36rpx;
			position: absolute;
			bottom: 150rpx;
			left: 20rpx;
		}

		// “添加标签” 弹出框
		.v-pop-cls {
			padding: 46rpx 0 88rpx;
			width: 710rpx;
			height: auto;
			position: relative;
			border-radius: 20rpx;
			background: #fff;

			image {
				width: 52rpx;
				height: 52rpx;
				position: absolute;
				padding: 30rpx;
				top: 0rpx;
				right: 0rpx;
			}

			text {
				color: #000;
				font-size: 36rpx;
			}

			input {
				// text-align: center;
				padding: 0 20rpx;
				width: 608rpx;
				height: 94rpx;
				margin: 62rpx 0;
				border-radius: 20rpx;
				background: #f5f5f5;
			}

			view {
				width: 638rpx;
				height: 88rpx;
				background: linear-gradient(90deg, #0ac364 0%, #14df79 100%);
				// background: #1890ff;
				color: #fff;
				font-size: 32rpx;
			}
		}
	}
</style>